//
//  UIImageView+FIDDownLoadImage.m
//  FIDDownLoadImage
//
//  Created by Fidetro on 16/4/4.
//  Copyright © 2016年 Fidetro. All rights reserved.
//

#import "UIImageView+FIDDownLoadImage.h"
#import <CommonCrypto/CommonDigest.h>
#define  FOLDERPATH  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"FIDImageCache"]
@interface NSString (MD5)
+ (NSString *)getMd5_32Bit_String:(NSString *)srcString;
@end
@implementation NSString (MD5)
+ (NSString *)getMd5_32Bit_String:(NSString *)srcString{
    const char *cStr = [srcString UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr,
           (CC_LONG)strlen(cStr), digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    
    return result;
}
@end

@implementation UIImageView (FIDDownLoadImage)
static NSMutableDictionary *RAMdict;//存放内存图片的字典
static NSMutableDictionary *operationDic;//记录已经在下载的图片字典
static BOOL usedCaches = YES;
static BOOL usedMemory = YES;

+ (void)initialize
{
    RAMdict = [NSMutableDictionary dictionary];
    
    operationDic = [NSMutableDictionary dictionary];
}
- (void)setFIDdownloadImageTaskURLWithString:(NSString *)urlString placeholderImage:(UIImage *)defaultImage{
    
    
    NSFileManager *manager = [NSFileManager defaultManager];
    self.image = defaultImage;
    NSString *md5UrlString = [NSString getMd5_32Bit_String:urlString];
    if (![manager fileExistsAtPath:FOLDERPATH]) {
        [manager createDirectoryAtPath:FOLDERPATH withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *caches = [NSString stringWithFormat:@"%@/%@",FOLDERPATH,md5UrlString];
    
    NSLog(@"%@",caches);
    
    if (!(RAMdict[urlString] == nil)&&usedMemory == YES) {
        
        self.image = RAMdict[urlString];
        NSLog(@"内存");
    }else{
        if ([manager fileExistsAtPath:caches]&&usedCaches == YES) {
            
            self.image = [UIImage imageWithContentsOfFile:caches];
            [RAMdict setObject:self.image forKey:urlString];
            NSLog(@"闪存");
            
        }else{
            
            //下载图片
            NSOperationQueue *queue =[[NSOperationQueue alloc]init];
            NSBlockOperation *downloadOperation = [operationDic objectForKey:urlString];
            if (!downloadOperation) {
                //创建一个操作
                downloadOperation = [NSBlockOperation blockOperationWithBlock:^{
                    NSURL *url = [NSURL URLWithString:urlString];
                    NSData *data = [NSData dataWithContentsOfURL:url];
                    if (data) {
                        UIImage *image = [UIImage imageWithData:data];
                        
                        [data writeToFile:caches atomically:YES];
                        
                        
                        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                            [RAMdict setObject:image forKey:urlString];
                            self.image = image;
                            NSLog(@"网络");
                            
                            [operationDic removeObjectForKey:urlString];
                        }];
                        
                    }
                }];
                [queue addOperation:downloadOperation];
                
                [operationDic setObject:downloadOperation forKey:urlString];
                
            }
        }
    }
}

+(void)useCaches:(BOOL)isUsed{
    usedCaches =isUsed;
}
+(void)useMemory:(BOOL)isUsed{
    usedMemory = isUsed;
}
+ (void)removeAllImageInCaches{
    NSFileManager *manager =[NSFileManager defaultManager];
    [manager removeItemAtPath:FOLDERPATH error:nil];
}
+ (void)removeImageInCaches:(NSString *)urlPath{
    NSFileManager *manager =[NSFileManager defaultManager];
    [manager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",FOLDERPATH,[NSString getMd5_32Bit_String:urlPath]] error:nil];
}



@end
